package com.tencent.qf.activity.special.area.service.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tencent.qf.activity.special.area.service.dal.DO.JdGiftCouponTransferInfo;
import com.tencent.qf.activity.special.area.service.dal.DO.TsGiftCouponOrderRecord;
import com.tencent.qf.activity.special.area.service.dal.mapper.JdGiftCouponTransferInfoMapper;
import com.tencent.qf.activity.speical.area.api.dto.JdGiftCouponTransferCountDTO;
import com.tencent.qf.activity.speical.area.api.dto.JdGiftCouponTransferInfoDTO;
import com.tencent.qf.activity.special.area.service.service.JdGiftCouponTransferInfoService;
import com.tencent.qf.activity.speical.area.api.dto.req.SpecialAreaCouponRequest;
import com.tencent.qf.activity.speical.area.api.dto.req.TransferUserListReq;
import com.tencent.qf.common.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author p_haojiawu
 * @description 针对表【t_jd_gift_coupon_transfer_info(转链信息表)】的数据库操作Service实现
 * @createDate 2023-08-18 18:54:46
 */
@Service
@Slf4j
public class JdGiftCouponTransferInfoServiceImpl extends ServiceImpl<JdGiftCouponTransferInfoMapper, JdGiftCouponTransferInfo>
        implements JdGiftCouponTransferInfoService {

    @Resource
    private JdGiftCouponTransferInfoMapper jdGiftCouponTransferInfoMapper;

    @Resource
    private TsGiftCouponOrderRecordServiceImpl tsGiftCouponOrderRecordService;

    @Override
    public JdGiftCouponTransferCountDTO getTransferCount(String specialAreaId, Date transferTime) {
        QueryWrapper<JdGiftCouponTransferInfo> query = new QueryWrapper<>();
        query.eq("special_area_key", specialAreaId)
                .isNull("delete_time")
                .ge("create_time", transferTime);
        List<JdGiftCouponTransferInfo> jdGiftCouponTransferInfos = jdGiftCouponTransferInfoMapper.selectList(query);
        // 根据SpecialGoodsId分组统计
        Map<String, Long> groupBySpecialGoodsId = jdGiftCouponTransferInfos.stream()
                .collect(Collectors.groupingBy(JdGiftCouponTransferInfo::getSpecialGoodsId, Collectors.counting()));

        JdGiftCouponTransferCountDTO jdGiftCouponTransferCountDTO = new JdGiftCouponTransferCountDTO();
        jdGiftCouponTransferCountDTO.setAreaCount(jdGiftCouponTransferInfos.size());
        jdGiftCouponTransferCountDTO.setGroupByGoodsIdCount(groupBySpecialGoodsId);

        return jdGiftCouponTransferCountDTO;
    }

    @Override
    public List<JdGiftCouponTransferInfo> userTransferLinkedRecordBySku(SpecialAreaCouponRequest specialAreaCouponReq, Date queryStartTime) {
        QueryWrapper<JdGiftCouponTransferInfo> query = new QueryWrapper<>();
        query.eq("special_area_key", specialAreaCouponReq.getSpecialAreaKey())
                .isNull("delete_time")
                .eq("uid", specialAreaCouponReq.getIrisUid())
                .eq("sku_id", specialAreaCouponReq.getSkuId())
                .ge("create_time", queryStartTime);
        if (Objects.nonNull(specialAreaCouponReq.getAwardPoolId())) {
            query.eq("award_pool_id", specialAreaCouponReq.getAwardPoolId());
        }
        return jdGiftCouponTransferInfoMapper.selectList(query);
    }

    @Override
    public Long getGoodsTransferCount(Long specialAreaGoodsId, Date transferTime) {
        QueryWrapper<JdGiftCouponTransferInfo> query = new QueryWrapper<>();
        query.eq("special_goods_id", specialAreaGoodsId)
                .isNull("delete_time")
                .ge("create_time", transferTime);

        return jdGiftCouponTransferInfoMapper.selectCount(query);
    }

    @Override
    public List<JdGiftCouponTransferInfo> transferUserList(TransferUserListReq request) {
        QueryWrapper<JdGiftCouponTransferInfo> query = new QueryWrapper<>();
        query.eq("uid", request.getUid());
        if (StringUtils.isNotBlank(request.getSpecialAreaId())){
            query.eq("special_area_key", request.getSpecialAreaId());
        }
        if (StringUtils.isNotBlank(request.getOutTradeNo())){
            query.eq("out_trade_no", request.getOutTradeNo());
        }
        query.isNull("delete_time")
                .orderByDesc("create_time");

        List<JdGiftCouponTransferInfo> jdGiftCouponTransferInfos = jdGiftCouponTransferInfoMapper.selectList(query);
        return jdGiftCouponTransferInfos;
    }

    @Override
    public List<JdGiftCouponTransferInfoDTO> getTransferInfo(String specialAreaId, String uid) {
        QueryWrapper<JdGiftCouponTransferInfo> query = new QueryWrapper<>();
        query.eq("special_area_key", specialAreaId)
                .eq("uid", uid)
                .isNull("delete_time")
                .orderByDesc("create_time");

        List<JdGiftCouponTransferInfo> jdGiftCouponTransferInfos = jdGiftCouponTransferInfoMapper.selectList(query);

        // 根据批次号过滤
        Map<String, JdGiftCouponTransferInfo> giftKeyMap = jdGiftCouponTransferInfos.stream()
                .collect(Collectors.toMap(JdGiftCouponTransferInfo::getGiftCouponKey, jdGiftCouponTransferInfo -> jdGiftCouponTransferInfo, (k1, k2) -> k1));

        log.info("用户:{},专区:{}, 转链批次号:{}", uid, specialAreaId, JSON.toJSONString(giftKeyMap.keySet()));

        if(giftKeyMap.keySet().size() == 0){
            return Collections.emptyList();
        }

        // 获取已核销的批次号
        List<TsGiftCouponOrderRecord> couponUsed = tsGiftCouponOrderRecordService.getCouponUsed(uid, new ArrayList<>(giftKeyMap.keySet()));
        HashSet<String> couponUsedKeys = couponUsed.stream().map(TsGiftCouponOrderRecord::getGiftKey)
                .collect(Collectors.toCollection(HashSet::new));

        log.info("用户:{},专区:{}, 已核销批次号:{}", uid, specialAreaId, JSON.toJSONString(couponUsed));

        List<JdGiftCouponTransferInfoDTO> jdGiftCouponTransferInfoDTOS = new ArrayList<>();
        for (JdGiftCouponTransferInfo jdGiftCouponTransferInfo : giftKeyMap.values()) {
            // 今日转链||已核销
            if(jdGiftCouponTransferInfo.getCreateTime().after(DateUtils.getCurrentDayFirstSecondTime())
                || couponUsedKeys.contains(jdGiftCouponTransferInfo.getGiftCouponKey())) {
                JdGiftCouponTransferInfoDTO jdGiftCouponTransferInfoDTO = new JdGiftCouponTransferInfoDTO();
                BeanUtils.copyProperties(jdGiftCouponTransferInfo, jdGiftCouponTransferInfoDTO);
                jdGiftCouponTransferInfoDTO.setIsUsed(couponUsedKeys.contains(jdGiftCouponTransferInfoDTO.getGiftCouponKey()));
                jdGiftCouponTransferInfoDTOS.add(jdGiftCouponTransferInfoDTO);
            }
        }

        return jdGiftCouponTransferInfoDTOS;
    }
}




